<template>
  <div class="app-container">
    <el-form ref="unit" :model="queryParams" label-width="80px" :inline="true" v-show="showSearch">
      <el-form-item label="产品编号">
        <el-input v-model="queryParams.code"></el-input>
      </el-form-item>
      <el-form-item label="产品名称">
        <el-input v-model="queryParams.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExcel_export">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-download" size="mini" @click="handleExcel_import">导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品编码" align="center" prop="productCode" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="单位" align="center" prop="productUnitName" />
      <el-table-column label="线体" align="center" prop="processrouteName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" class="delred">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :v-show="true" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改单位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="dmlform" :model="dmlform" :rules="rules" label-width="150px">
        <el-form-item label="产品编码" prop="productCode">
          <el-input v-model="dmlform.productCode" placeholder="请输入产品编码" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="dmlform.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="单位" prop="measureName">
          <el-autocomplete
            v-model="dmlform.productUnitName"
            :fetch-suggestions="querymeasureNameAsync"
            placeholder="请输入单位名称"
            @select="handlemeasureNamSelect"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="工艺路线" prop="processrouteName">
          <el-autocomplete
            v-model="dmlform.processrouteCodeName"
            :fetch-suggestions="queryprocessrouteNameAsync"
            placeholder="请输入工艺路线"
            @select="handleProcessrouteNameSelect"
          ></el-autocomplete>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导出excel筛选 -->
    <el-dialog title="导出excel筛选" :visible.sync="exportopen" width="600px" append-to-body>
      <el-form ref="exportExcel" :model="exportExcel" label-width="150px" label-position="left" :rules="exportRules">
        <el-form-item label="查询时间" prop="excelTime">
          <el-date-picker
            v-model="exportExcel.excelTime"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="center"
        /></el-form-item>
        <el-form-item label="产品编码" prop="productCode">
          <el-input v-model="exportExcel.productCode" placeholder="输入产品名称"></el-input>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="exportExcel.productName" placeholder="输入产品名称"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitExcelForm">导出</el-button>
        <el-button @click="exportopen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 产品上传对话框 -->
    <el-dialog title="上传产品" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip"><el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的设备数据</div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listproductEfinition,
  addProductDefine,
  getUnitmeasure,
  getProcessroute,
  updateProductDefine,
  getProductBypk,
  delproduct,
  exportProduct,
} from '@/api/basisManagement/productEfinition.js'
import { getToken } from '@/utils/auth'
import { debounce } from '@/utils'

export default {
  name: 'unit',
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      // 遮罩层
      loading: false,
      // 非单个禁用
      single: true,
      multiple: false,
      total: 1,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        code: null,
        name: null,
      },
      //产品列表
      productList: [],
      //模态框名称
      title: '新增',
      open: false,
      exportopen: false,
      dmlform: {
        productCode: '',
        productName: '',
        measureId: '', //unit表
        productUnit: '', //product表
        productUnitName: '', //product表
        workline:null
      },
      rules: {
        productCode: [{ required: true, message: '产品编码不能为空', trigger: 'blur' }],
        productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
        productUnitName: [{ required: true, message: '单位名称不能为空', trigger: 'blur' }],
      },
      exportRules: {
        excelTime: [{ required: true, message: '时间不能为空', trigger: 'blur' }],
      },
      ids: [],
      idsName: [],
      exportExcel: {
        excelTime: [],
        productCode: '',
        productName: '',
      },

      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            },
          },
        ],
      },
      //上传配置
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '上传',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/mes/md/product/importExcel',
      },
    }
  },
  created() {
    this.getList()
  },

  methods: {
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.code = null
      this.queryParams.name = null
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleAdd() {
      this.reset()
      this.title = '新增'
      this.open = true
    },
    handleUpdate(row) {
  
    
      this.reset()
      this.open = true
      this.title = '修改'
      const id = row.id || this.ids

      getProductBypk(id).then((response) => {
        this.dmlform = response.data
      })
      //ProductUnitName
    },
    handleDelete(row) {
      const id = row.id || this.ids
      const idsName = row.productName || this.idsName
      this.$modal
        .confirm('是否确认删除单位编号为"' + idsName + '"的数据项？')
        .then(function () {
          return delproduct(id)
        })
        .then((response) => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },

    // 获取list
    getList() {
      this.loading = true
      listproductEfinition(this.queryParams).then((response) => {
        this.productList = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.idsName = selection.map((item) => item.productName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    submitForm() {
      this.$refs['dmlform'].validate((valid) => {
        if (valid) {
          if (this.dmlform.id != null || this.dmlform.id == '') {
            updateProductDefine(this.dmlform).then((response) => {
              if (response.data == 1) {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
                this.reset()
              }
            })
          } else {
            //新增
            let data = new Object()
            data.productCode = this.dmlform.productCode
            data.productName = this.dmlform.productName
            data.productUnit = this.dmlform.productUnit
            data.productUnitName = this.dmlform.productUnitName
            data.productUnitName = this.dmlform.productUnitName
            data.processrouteCodeName = this.dmlform.processrouteCodeName
            data.ProcessrouteId = this.dmlform.ProcessrouteId

            addProductDefine(data).then((response) => {
              if (response.data == 1) {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
              } else {
                this.$notify.error('新增失败')
              }
            })
          }
        }
      })
    },
    //取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      ;(this.dmlform = {
        productCode: '',
        productName: '',
        measureId: '', //unit表
        productUnit: '', //product表
        productUnitName: '', //product表
        processrouteCodeName: '',
        ProcessrouteId: '',
      }),
        this.resetForm('dmlform')
    },

    //excel导出
    handleExcel_export() {
      this.exportopen = true
    },

    submitExcelForm() {
      this.$refs['exportExcel'].validate(async (valid) => {
        if (valid) {
          this.exportExcel.starttime = this.exportExcel.excelTime[0]
          this.exportExcel.endtime = this.exportExcel.excelTime[1]
          await exportProduct(this.exportExcel)
          this.exportopen = false
        }
      })
    },

    // 远程搜索单位
    querymeasureNameAsync(queryString, cb) {
      if (queryString == undefined) {
        queryString = ''
      }
      getUnitmeasure(queryString).then((res) => {
        const data = []
        for (let i of res.data) {
          data.push({
            measureId: i.measureId,
            value: i.measureName,
          })
        }
        //键值对
        cb(data)
      })
    },
    //处理单位选择
    handlemeasureNamSelect(row) {
      this.dmlform.productUnit = row.measureId
    },
    //搜索远程工艺路线
    queryprocessrouteNameAsync(queryString, cb) {
      if (queryString == undefined) {
        queryString = ''
      }
      getProcessroute(queryString).then((res) => {
        const data = []
        for (let i of res.data) {
          data.push({
            id:i.id,
            lineCode: i.lineCode,
            lineName:i.lineName,
            value: i.lineCode+"|"+i.lineName,
          })
        }
        //键值对
        cb(data)
      })
    },
    // 工艺路线选择事件
    handleProcessrouteNameSelect(data) {   
     const  str = {
        id:data.id,
        lineCode:data.lineCode,
        lineName:data.lineName
      }

      
      this.dmlform.workline=JSON.stringify(str);




    },

    //导入excel
    handleExcel_import() {
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
        dangerouslyUseHTMLString: true,
      })
      this.getList()
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },

    /** 下载模板操作 */
    importTemplate() {
      this.download('mes/dv/product/importTemplate', {}, `md_item_${new Date().getTime()}.xlsx`)
    },
  },
}
</script>

<style lang="scss" scoped>
.delred {
  ::v-deep .el-icon-delete {
    color: #f56c6c;
  }
  ::v-deep span {
    color: #f56c6c;
  }
}
</style>
